from django.contrib import admin
from django.db import models
from django.utils.html import format_html
from jsoneditor.forms import JSONEditor


# Register your models here.

from .models import Category,Dish,DishFlavor


# 内联模型 - 嵌套用
class Flavor(admin.StackedInline):
    model = DishFlavor
    extra = 1
    # json字段默认展示的是文本框，这里使用对应插件展示成json
    formfield_overrides = {
        models.JSONField: {"widget": JSONEditor},
    }
    verbose_name_plural = "菜品口味"

class CategoryManagerAdmin(admin.ModelAdmin):
    list_display = ('name', 'sort', 'create_time')

class DishManagerAdmin(admin.ModelAdmin):
    list_display = ('name', 'category', 'image', 'price', 'status', 'create_time')
    #设置可编辑字段
    list_editable = ('status','category')
    search_fields = ('name',)
    search_help_text = '输入菜品名称进行搜索'

    list_filter = ('category', 'status')
    # 嵌套子模型 口味， 在添加商品时直接就把口味一起加了
    inlines = [Flavor]

    # 增加一个字段
    def show_img(self, obj):
        """
        :param obj: obj 为 一个Dish 的实例对象
        :return:
        """
        if obj.image:
            # obj.image.url 获取从midia的路径 /media/product/XXXX.png
            # print(obj.image.url)
            return format_html('<img src="{}" height="50"/>'.format(obj.image.url))
        else:
            return ''

    # 字段列表表头显示
    show_img.short_description = '图片'

   
class DishFlavorManagerAdmin(admin.ModelAdmin):
    list_display = ('name', 'dish', 'create_time')
    

admin.site.register(Category,CategoryManagerAdmin)
admin.site.register(Dish,DishManagerAdmin)
admin.site.register(DishFlavor,DishFlavorManagerAdmin)